﻿using DoNetDrive.Common.Extensions;
using FaceWebServer.DB;
using FaceWebServer.DB.TimeGroup;
using FaceWebServer.Interface;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;

namespace FaceWebServer.Service
{
    /// <summary>
    /// 设备远程操作服务
    /// </summary>
    public class DeviceRemoteService : BaseService, IDeviceRemoteService
    {
        public DeviceRemoteService(DbContext context) : base(context)
        {
        }

        public RemoteTaskDetail Add(RemoteTaskDetail newTask)
        {
            newTask.CreateTime = System.DateTime.Now;
            newTask.LastUpdatetime = System.DateTime.Now;
            newTask.TaskRunTime = System.DateTime.Now;
            newTask.TaskStatus = 0;
            Insert(newTask);
            AddUserLog("设备远程操作", $"新增设备远程操作任务： 详情：{newTask.ToJSON()}");
            return newTask;
        }

        public RemoteTaskDetail Delete(int taskID)
        {

            RemoteTaskDetail dtl = Find<RemoteTaskDetail>(taskID);

            if (dtl != null)
            {
                dtl.LastUpdatetime = System.DateTime.Now;
                AddUserLog("设备远程操作", $"删除设备远程操作任务： 详情：{dtl.ToJSON()}");
                Delete(dtl);
                return dtl;
            }
            else
            {
                return null;
            }

        }

        public List<RemoteTaskDetail> GetRemoteTaskByDeviceID(int iDeviceID)
        {
            return Query<RemoteTaskDetail>(x => x.DeviceID == iDeviceID && x.TaskStatus == 0)
                .Take(1).ToList();
        }

        public void UpdateTaskRunStatusComplete(int iDeviceID, int iTaskType)
        {
            var lst =Query<RemoteTaskDetail>(x => x.DeviceID == iDeviceID && x.TaskStatus == 0 && x.TaskType == iTaskType);
            foreach (var detail in lst)
            {
                detail.TaskStatus = 1;
                detail.TaskRunTime = System.DateTime.Now;
                Update<RemoteTaskDetail>(detail);
            }
        }
    }
}
